/**
 * 
 */
package cn.springsoter.core.launch.config;

import java.time.Duration;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import lombok.extern.slf4j.Slf4j;

/**
 * @Async 异步线程配置类
 * 
 * @author kevin
 *
 */
@Slf4j
@EnableScheduling
@EnableAsync
@Configuration
public class AsyncConfig implements AsyncConfigurer {
	@Value("${spring.task.execution.pool.core-size:16}")
	private int corePoolSize;
	
	@Value("${spring.task.execution.pool.max-size:32}")
	private int maxPoolSize;
	
	@Value("${spring.task.execution.pool.keep-alive:60S}")
	private Duration keepAliveSeconds;

	@Value("${spring.task.execution.pool.queue-capacity:100}")
	private int queueCapacity;
	
	@Value("${spring.task.execution.thread-name-prefix:springsoter-}")
	private String threadNamePrefix;
	
	@Bean
	public TaskExecutor taskExecutor() {
		ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
		// 设置核心线程数
        executor.setCorePoolSize(corePoolSize);
        // 设置最大线程数
        executor.setMaxPoolSize(maxPoolSize);
        // 设置队列容量
        executor.setQueueCapacity(queueCapacity);
        // 设置线程活跃时间（秒）
        executor.setKeepAliveSeconds(((Long)keepAliveSeconds.getSeconds()).intValue());
        // 设置默认线程名称
        executor.setThreadNamePrefix(threadNamePrefix);
        // 设置拒绝策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
        // 等待所有任务结束后再关闭线程池
        executor.setWaitForTasksToCompleteOnShutdown(false);
		return executor;
	}
	
	@Override
	public Executor getAsyncExecutor() {
		return taskExecutor();
	}

	@Override
	public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
		return (ex, method, params) -> {
			log.error(String.format("【执行异步任务'%s'】", method), ex);
		};
	}
	
}
